#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:1静态web服务器.py
# author: 马国鑫
# datetime:2022/4/18 21:49
# software: PyCharm

"""
this is function  description 
"""

# import module your need

import socket

# 创建电话
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 端口复用
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

# 绑定地址
tcp_server_socket.bind(("", 8080))

# 设置监听
tcp_server_socket.listen(128)

while True:
    # 等待接受
    client_socket, addr = tcp_server_socket.accept()
    recv_data = client_socket.recv(1000000)

    print(recv_data.decode())
    if len(recv_data) == 0:
        print('客户端关闭')
        break

    # 打开资源文件,二进制打开
    f = open('./static/1398.jpg', 'rb')
    # 存放了图片资源
    file_data = f.read()
    f.close()

    # 组装响应报文
    # 响应行
    response_line = "HTTP/1.1 200 OK\r\n"
    response_header = "server:py1.0\r\n"
    response_body = file_data

    response_data = (response_line + response_header + "\r\n").encode() + response_body

    # 发送数据
    client_socket.send(response_data)
    # 关闭
    client_socket.close()


